import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import Input from '@/components/Input';
import { useFormik } from 'formik';
// 有些第三方包，没有设置export default，下方相当于把所有的export 合并为一个对象Yup
import * as Yup from 'yup';
import { useAppDispatch } from '@/store';
import { loginAction, sendCodeAction } from '@/store/action/login';
import { useEffect, useRef, useState } from 'react';
import { Toast } from 'antd-mobile';
import { useHistory, useLocation } from 'react-router-dom';

export default function Login() {
  const dispatch = useAppDispatch();
  const [second, setSecond] = useState(0);
  const timeIdRef = useRef<number>();
  const history = useHistory();
  //获取跳转过来的地址
  const { state } = useLocation();
  const { from } = (state as { from: string }) || {};
  useEffect(() => {
    return () => {
      clearInterval(timeIdRef.current);
    };
  }, []);

  const handSendCode = () => {
    dispatch(sendCodeAction(formik.values.mobile));
    setSecond(60);
    timeIdRef.current = window.setInterval(() => {
      setSecond((prev) => {
        if (prev === 1) {
          clearInterval(timeIdRef.current);
        }
        return prev - 1;
      });
    }, 10);
  };
  const formik = useFormik({
    //初始化数据
    initialValues: {
      mobile: '',
      code: '',
    },
    //提交数据
    onSubmit: async (values) => {
      await dispatch(loginAction(values.mobile, values.code));
      Toast.show({
        icon: 'success',
        content: '登录成功',
      });
      setTimeout(() => {
        //有历史页面就跳转到历史页面，没有就跳转到首页
        history.replace(from || '/');
      }, 500);
    },
    //检验数据
    validationSchema: Yup.object().shape({
      mobile: Yup.string()
        .required('手机号不能为空')
        .matches(/^1[3-9]\d{9}$/, '手机号格式不正确'),
      code: Yup.string()
        .required('验证码不能为空')
        .matches(/^\d{6}$/, '验证码格式不正确'),
    }),
    // validate: (values) => {
    //   console.log(values);
    //   const errors = {} as typeof values;
    //   if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
    //     errors.mobile = '手机号格式不正确';
    //   }
    //   if (!/^\d{6}$/.test(values.code)) {
    //     errors.code = '验证码格式不正确';
    //   }
    //   return errors;
    // },
  });
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                autoFocus
                placeholder="请输入手机号"
                autoComplete="off"
                type="text"
                name="mobile"
                maxLength={11}
                errMsg={formik.errors.mobile}
                onChange={formik.handleChange}
                value={formik.values.mobile}
                onBlur={formik.handleBlur}
              />
            </div>
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <Input
              placeholder="请输入验证码"
              autoComplete="off"
              type="text"
              name="code"
              maxLength={6}
              extra={
                second === 0 ? (
                  <div className="extra" onClick={handSendCode}>
                    获取验证码
                  </div>
                ) : (
                  <div className="extra">{second}秒后获取</div>
                )
              }
              errMsg={formik.errors.code}
              onChange={formik.handleChange}
              value={formik.values.code}
              onBlur={formik.handleBlur}
            />
          </div>

          {/* 登录按钮 */}
          <button type="submit" className="login-btn" disabled={!formik.isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
